package selectionweb.web.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import selectionweb.web.Ingredient;
import selectionweb.web.Ingredient.Type;
import selectionweb.web.Student;
import selectionweb.web.Course;
import selectionweb.web.repository.CourseRepository;
import selectionweb.web.repository.IngredientRepository;


import javax.validation.Valid;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

@Slf4j
@Controller
@Configuration
@Validated
@RequestMapping("/selection")
@SessionAttributes("course")
public class SelectionController {

        private IngredientRepository ingredientRepository;

        private CourseRepository courseRepository;

    public SelectionController(
                IngredientRepository ingredientRepository,
                CourseRepository tacoRepository
        ){
            this.ingredientRepository=ingredientRepository;
            this.courseRepository=tacoRepository;
        }


        @GetMapping
        public String showDesignForm(Model model) {
            List<Ingredient> ingredients = new ArrayList<>();
            ingredientRepository.findAll().forEach(i -> ingredients.add(i));

            Type[] types = Ingredient.Type.values();
            for (Type type : types) {
                model.addAttribute(type.toString().toLowerCase(),
                        filterByType(ingredients, type));
            }
            return "selection";
        }

    @Validated
    @PostMapping
    public String processDesign(@Valid Course course, Errors errors, Model model, SessionStatus sessionStatus) {
        if (errors.hasErrors()) {
            return "selection";
        }
        courseRepository.save(course);
        sessionStatus.setComplete();
        return "selectionResult";
    }

    private List<Ingredient> filterByType(
            List<Ingredient> ingredients, Type type) {
        return ingredients
                .stream()
                .filter(x -> x.getType().equals(type))
                .collect(Collectors.toList());
    }
}


